package cn.com.gridinfo.sooc.core.expand.signin.fragment;

import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.jeremy.arad.utils.Log;
import com.jeremy.arad.utils.StringUtils;
import com.marshalchen.ultimaterecyclerview.UltimateRecyclerView;

import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;
import butterknife.OnTextChanged;
import cn.com.gridinfo.sooc.R;
import cn.com.gridinfo.sooc.base.BaseSoocFragment;
import cn.com.gridinfo.sooc.core.expand.callname.common.CodeConst;
import cn.com.gridinfo.sooc.core.expand.callname.common.PageConst;
import cn.com.gridinfo.sooc.core.expand.callname.dao.CallNameDao;
import cn.com.gridinfo.sooc.core.expand.signin.adapter.HistorySignAdapter;
import cn.com.gridinfo.sooc.utils.MessageUtils;
import cn.com.gridinfo.sooc.utils.widget.ClearEditText;

/**
 * 历史签到的Fragment
 *
 * @author yingchunli
 */
public class HistorySignFragment extends BaseSoocFragment {

    View view;//当前布局
    @InjectView(R.id.search_content_historysign)
    ClearEditText searchContent;//搜索内容
    @InjectView(R.id.count_historysign)
    TextView countHistorysign;//签到结果数量
    @InjectView(R.id.sign_result)
    LinearLayout signResult;//签到总数 行
    @InjectView(R.id.searchCount_historysign)
    TextView searchCount;//搜索结果数量
    @InjectView(R.id.search_result)
    RelativeLayout searchResult;//搜索结果  行
    @InjectView(R.id.list_historysign)
    UltimateRecyclerView listHistorysign;//列表
    LinearLayoutManager linearLayoutManager;//布局管理器
    HistorySignAdapter adapter;//适配器
    CallNameDao dao;
    int maxLastPositon;//数据最后位置
    @InjectView(R.id.ll_no_data)
    LinearLayout layout;//空白页布局

    public static HistorySignFragment newInstance(String info) {
        Bundle args = new Bundle();
        HistorySignFragment fragment = new HistorySignFragment();
        args.putString("info", info);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.expand_historysign, null);
        ButterKnife.inject(this, view);
        dao = new CallNameDao(this);
        linearLayoutManager = new LinearLayoutManager(getActivity());
        listHistorysign.setLayoutManager(linearLayoutManager);
        PageConst.pageNo = 1;
        PageConst.pageSize = 10;
        //发送请求  获取列表
        dao.getMySign(1, null, PageConst.pageNo, PageConst.pageSize, CodeConst.EXPAND_GET_SIGNLIST_FIRST);

        //按键完成监听
        searchContent.setImeOptions(EditorInfo.IME_ACTION_SEARCH);
        searchContent.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    onSearchClick();
                }
                return false;
            }
        });
        return view;
    }

    /**
     * 关闭搜索区域
     */
    @OnClick(R.id.close_search)
    void closeSearchContainer() {
        searchResult.setVisibility(View.GONE);
    }

    /**
     * 无数据时，空白页的处理
     */
    void setBlankView(String search) {

        ImageView imageView = (ImageView) view.findViewById(R.id.iv_no_data);
        TextView textView = (TextView) view.findViewById(R.id.tv_no_data);
        if (search.equals("search")) {
            imageView.setImageResource(R.mipmap.blank_search);
            textView.setText("没有找到相关课堂");
        } else {
            imageView.setImageResource(R.mipmap.blank_sign);
            textView.setText("没有签到历史");
        }
    }

    /**
     * 搜索内容从有到空，需要重新加载列表
     */
    @OnTextChanged(value = {R.id.search_content_historysign},
            callback = OnTextChanged.Callback.AFTER_TEXT_CHANGED)
    void onAfterTextChanged() {
        if (searchContent.getText().toString().trim().equals("")) {
            PageConst.pageNo = 1;
            PageConst.pageSize = 10;
            //发送请求  获取列表
            dao.getMySign(1, null, PageConst.pageNo, PageConst.pageSize, CodeConst.EXPAND_GET_SIGNLIST_PUSHDOWN);
        }
    }

    /**
     * 初始化界面数据
     */
    private void initView() {
        adapter = new HistorySignAdapter(getActivity(), dao.getClassInfoList());
        listHistorysign.setAdapter(adapter);
        listHistorysign.enableLoadmore();
        listHistorysign.setDefaultOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                PageConst.pageNo = 1;
                if (searchContent.getText().toString().isEmpty()) {
                    //搜索内容为空 ，表明是获取列表
                    dao.getMySign(1, null, PageConst.pageNo, PageConst.pageSize, CodeConst.EXPAND_GET_SIGNLIST_PUSHDOWN);
                } else {
                    //搜索内容不为空时，表明是搜索列表数据
                    dao.getMySign(1, searchContent.getText().toString().trim(), PageConst.pageNo, PageConst.pageSize, CodeConst.EXPAND_GET_SIGNLIST_PUSHDOWN);
                }
                linearLayoutManager.scrollToPosition(0);
            }
        });
        listHistorysign.setOnLoadMoreListener(new UltimateRecyclerView.OnLoadMoreListener() {
            @Override
            public void loadMore(final int itemsCount, final int maxLastVisiblePosition) {
                if (itemsCount > (PageConst.pageSize - 1)) {
                    maxLastPositon = maxLastVisiblePosition;
                    if (searchContent.getText().toString().isEmpty()) {
                        //搜索内容为空 ，表明是获取列表
                        dao.getMySign(1, null, ++PageConst.pageNo, PageConst.pageSize, CodeConst.EXPAND_GET_SIGNLIST_PULLUP);
                    } else {
                        //搜索内容不为空时，表明是搜索列表数据
                        dao.getMySign(1, searchContent.getText().toString().trim(), ++PageConst.pageNo, PageConst.pageSize, CodeConst.EXPAND_GET_SIGNLIST_PULLUP);
                    }
                } else {
                    adapter.loadNoDataView();
                    linearLayoutManager.scrollToPositionWithOffset(maxLastVisiblePosition, -1);
                }
            }
        });
    }

    @Override
    public void onRequestSuccess(int requestCode) {
        try {
            if (dao.getStatus().equals("0")) {
                switch (requestCode) {
                    case CodeConst.EXPAND_GET_SIGNLIST_FIRST://获取列表 首次请求
                        initView();
                        if (dao.getClassInfoList() != null && !dao.getClassInfoList().isEmpty()) {
                            listHistorysign.hideEmptyView();
                        } else {
                            listHistorysign.showEmptyView();
                            if (searchContent.getText().toString().isEmpty()) {//搜索内容为空时
                                setBlankView( "search_not");//显示空白页
                            } else {
                                setBlankView( "search");//显示空白页
                            }
                        }
                        Log.d("搜索内容：searchContent=" + searchContent.getText().toString().trim());
                        if (searchContent.getText().toString().isEmpty()) {
                            Log.d("搜索内容为空");
                            signResult.setVisibility(View.VISIBLE);//显示签到结果
                            searchResult.setVisibility(View.GONE);//隐藏搜索结果
                            countHistorysign.setText(dao.getCount() + "");//设置签到总数
                        } else {
                            Log.d("搜索内容 不为空");
                            signResult.setVisibility(View.GONE);//隐藏签到结果
                            searchResult.setVisibility(View.VISIBLE);//显示搜索结果
                            searchCount.setText(dao.getCount() + "");//设置搜索结果数量
                        }
                        break;
                    case CodeConst.EXPAND_GET_SIGNLIST_PUSHDOWN://获取列表  下拉请求

                        listHistorysign.setRefreshing(false);
                        if (dao.getClassInfoList() != null && !dao.getClassInfoList().isEmpty()) {
                            listHistorysign.hideEmptyView();

                        } else {
                            listHistorysign.showEmptyView();
                            //无数据处理
                            if (searchContent.getText().toString().trim().equals("")) {
                                //搜索内容为空时
                                setBlankView( "");
                            } else {
                                setBlankView( "search");
                            }
                        } //刷新数据
                        adapter.refresh(dao.getClassInfoList());

                        if (searchContent.getText().toString().isEmpty()) {
                            Log.d("搜索内容为空");
                            signResult.setVisibility(View.VISIBLE);//显示签到结果
                            searchResult.setVisibility(View.GONE);//隐藏搜索结果
                            countHistorysign.setText(dao.getCount() + "");//设置签到总数
                        } else {
                            Log.d("搜索内容 不为空");
                            signResult.setVisibility(View.GONE);//隐藏签到结果
                            searchResult.setVisibility(View.VISIBLE);//显示搜索结果
                            searchCount.setText(dao.getCount() + "");//设置搜索结果数量
                        }

                        if (dao.getClassInfoList().size() > (PageConst.pageSize - 1))
                            //数据大于每页显示的条数,则重新开启加载更多
                            adapter.loadMoreDataView();
                        else {
                            //数据小于当前页的话则不显示加载更多
                            adapter.loadNoDataView();
                            linearLayoutManager.scrollToPositionWithOffset(maxLastPositon, -1);
                            linearLayoutManager.scrollToPosition(maxLastPositon);
                        }
                        break;
                    case CodeConst.EXPAND_GET_SIGNLIST_PULLUP://获取列表  上拉请求
                        if (dao.getClassInfoList() != null && !dao.getClassInfoList().isEmpty()) {
                            //加载更多
                            adapter.loadmore(dao.getClassInfoList());
                        } else {
                            //无数据则不显示下一页
                            adapter.loadNoDataView();
                            linearLayoutManager.scrollToPositionWithOffset(maxLastPositon, -1);
                        }
                        break;
                }
            } else {
                MessageUtils.showImageShortToast(getActivity(), dao.getStatusCode());
            }
        } catch (Exception e) {
            MessageUtils.showImageShortToast(getActivity(), "请求数据异常");
        }
    }

    /**
     * 搜索 历史签到
     */
    @OnClick(R.id.searchbtn_histotysign)
    void onSearchClick() {
        if (!searchContent.getText().toString().trim().equals("")) {
            PageConst.pageNo = 1;
            PageConst.pageSize = 10;
            //发送请求  获取列表
            dao.getMySign(1, searchContent.getText().toString().trim(), PageConst.pageNo, PageConst.pageSize, CodeConst.EXPAND_GET_SIGNLIST_PUSHDOWN);
            //隐藏软键盘
            InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(searchContent.getWindowToken(), 0);
        }

    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.reset(this);
    }
}
